<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            padding: 20px;
            background-color: #f8f9fa;
        }
        .container {
            max-width: 1200px;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
        }
        .form-container {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .search-box {
            margin-bottom: 20px;
        }
        .table-container {
            margin-top: 20px;
            overflow-x: auto;
        }
        .pagination-info {
            margin-top: 10px;
            color: #6c757d;
        }
        .btn-action {
            margin-right: 5px;
        }
        .loading-spinner {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
        .error-message {
            color: #dc3545;
            text-align: center;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="my-4 text-center">学生信息管理系统</h1>
        
        <!-- 搜索框 -->
        <div class="search-box">
            <div class="row g-2">
                <div class="col-md-6">
                    <input type="text" id="searchName" class="form-control" placeholder="按姓名搜索">
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="searchGender">
                        <option value="">全部性别</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <button id="searchBtn" class="btn btn-primary">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                    <button id="resetBtn" class="btn btn-secondary">
                        <i class="bi bi-arrow-counterclockwise"></i> 重置
                    </button>
                    <button id="addBtn" class="btn btn-success">
                        <i class="bi bi-plus-lg"></i> 添加
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 学生表单 -->
        <div id="formContainer" class="form-container" style="display: none;">
            <form id="studentForm">
                <input type="hidden" id="studentId">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label for="name" class="form-label">姓名 *</label>
                        <input type="text" class="form-control" id="name" required>
                        <div class="invalid-feedback">请输入姓名</div>
                    </div>
                    <div class="col-md-2">
                        <label for="gender" class="form-label">性别 *</label>
                        <select class="form-select" id="gender" required>
                            <option value="">请选择</option>
                            <option value="男">男</option>
                            <option value="女">女</option>
                        </select>
                        <div class="invalid-feedback">请选择性别</div>
                    </div>
                    <div class="col-md-2">
                        <label for="age" class="form-label">年龄</label>
                        <input type="number" class="form-control" id="age" min="1" max="120">
                    </div>
                    <div class="col-md-3">
                        <label for="hometown" class="form-label">籍贯</label>
                        <input type="text" class="form-control" id="hometown">
                    </div>
                    <div class="col-md-3">
                        <label for="phone" class="form-label">电话</label>
                        <input type="text" class="form-control" id="phone">
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-success me-2">
                            <i class="bi bi-save"></i> 保存
                        </button>
                        <button type="button" id="cancelBtn" class="btn btn-warning">
                            <i class="bi bi-x-lg"></i> 取消
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- 加载指示器 -->
        <div id="loadingSpinner" class="loading-spinner">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p>正在加载数据，请稍候...</p>
        </div>
        
        <!-- 错误信息 -->
        <div id="errorMessage" class="error-message" style="display: none;"></div>
        
        <!-- 学生表格 -->
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>年龄</th>
                        <th>籍贯</th>
                        <th>电话</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="studentTableBody">
                    <tr>
                        <td colspan="6" class="text-center">正在加载数据...</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <!-- 分页控件 -->
        <div class="row mt-3">
            <div class="col-md-6">
                <div class="pagination-info">
                    显示 <span id="startItem">0</span> 到 <span id="endItem">0</span> 条，共 <span id="totalItems">0</span> 条
                </div>
            </div>
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-end" id="pagination">
                        <li class="page-item disabled">
                            <a class="page-link" href="#">加载中...</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    确定要删除这条学生记录吗？此操作不可撤销！
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-lg"></i> 取消
                    </button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">
                        <i class="bi bi-trash"></i> 删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap & jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- 主JavaScript代码 -->
    <script>
        // 全局变量
        let currentPage = 1;
        const pageSize = 10;
        let totalStudents = 0;
        let studentToDelete = null;
        const API_BASE_URL = 'http://localhost:8100'; // 修改为您的实际后端地址

        // DOM加载完成后执行
        $(document).ready(function() {
            // 初始化模态框
            const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
            
            // 加载学生数据
            loadStudents();
            
            // 搜索按钮事件
            $('#searchBtn').on('click', function() {
                currentPage = 1;
                loadStudents();
            });
            
            // 重置按钮事件
            $('#resetBtn').on('click', function() {
                $('#searchName').val('');
                $('#searchGender').val('');
                currentPage = 1;
                loadStudents();
            });
            
            // 添加按钮事件
            $('#addBtn').on('click', function() {
                resetForm();
                showStudentForm();
            });
            
            // 表单提交事件
            $('#studentForm').on('submit', function(e) {
                e.preventDefault();
                saveStudent();
            });
            
            // 取消按钮事件
            $('#cancelBtn').on('click', function() {
                hideStudentForm();
                resetForm();
            });
            
            // 删除确认按钮事件
            $('#confirmDelete').on('click', function() {
                if (studentToDelete) {
                    deleteStudent(studentToDelete);
                    studentToDelete = null;
                    deleteModal.hide();
                }
            });
        });

        // 显示表单
        function showStudentForm() {
            $('#formContainer').slideDown();
            $('#addBtn').hide();
        }

        // 隐藏表单
        function hideStudentForm() {
            $('#formContainer').slideUp();
            $('#addBtn').show();
        }

        // 显示加载指示器
        function showLoading() {
            $('#loadingSpinner').show();
            $('#errorMessage').hide();
            $('#studentTableBody').html(
                `<tr><td colspan="6" class="text-center">正在加载数据...</td></tr>`
            );
        }

        // 隐藏加载指示器
        function hideLoading() {
            $('#loadingSpinner').hide();
        }

        // 显示错误信息
        function showError(message) {
            $('#errorMessage').text(message).show();
            $('#studentTableBody').html(
                `<tr><td colspan="6" class="text-center">数据加载失败</td></tr>`
            );
        }

        // 加载学生数据
        function loadStudents() {
            showLoading();
            
            const name = $('#searchName').val();
            const gender = $('#searchGender').val();
            
            $.ajax({
                url: `${API_BASE_URL}/student/list`,
                method: 'GET',
                data: {
                    pageNum: currentPage,
                    pageSize: pageSize,
                    name: name,
                    gender: gender
                },
                success: function(data) {
                    if (data && data.list) {
                        totalStudents = data.total;
                        renderStudents(data.list);
                        renderPagination();
                        updatePaginationInfo();
                    } else {
                        showError('返回的数据格式不正确');
                    }
                },
                error: function(xhr, status, error) {
                    let errorMsg = '加载学生数据失败: ';
                    if (xhr.status === 0) {
                        errorMsg += '无法连接到服务器，请检查:';
                        errorMsg += '<br>1. 后端服务是否启动';
                        errorMsg += '<br>2. API地址是否正确: ' + API_BASE_URL;
                        errorMsg += '<br>3. 网络连接是否正常';
                    } else if (xhr.status === 404) {
                        errorMsg += 'API接口不存在 (404)';
                    } else if (xhr.status === 500) {
                        errorMsg += '服务器内部错误 (500)';
                    } else if (xhr.status === 403) {
                        errorMsg += '跨域请求被拒绝，请检查后端CORS配置';
                    } else {
                        errorMsg += `${xhr.status} ${error}`;
                    }
                    
                    showError(errorMsg);
                    console.error('API请求失败:', xhr);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 渲染学生表格
        function renderStudents(students) {
            const tbody = $('#studentTableBody');
            tbody.empty();
            
            if (!students || students.length === 0) {
                tbody.html(
                    '<tr><td colspan="6" class="text-center">没有找到学生数据</td></tr>'
                );
                return;
            }
            
            $.each(students, function(index, student) {
                const row = `
                    <tr>
                        <td>${student.id}</td>
                        <td>${student.name}</td>
                        <td>${student.gender}</td>
                        <td>${student.age || '-'}</td>
                        <td>${student.hometown || '-'}</td>
                        <td>${student.phone || '-'}</td>
                        <td>
                            <button class="btn btn-sm btn-primary edit-btn" data-id="${student.id}">
                                <i class="bi bi-pencil"></i> 编辑
                            </button>
                            <button class="btn btn-sm btn-danger delete-btn" data-id="${student.id}">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
            
            // 添加编辑按钮事件
            $('.edit-btn').on('click', function() {
                const studentId = $(this).data('id');
                editStudent(studentId);
            });
            
            // 添加删除按钮事件
            $('.delete-btn').on('click', function() {
                studentToDelete = $(this).data('id');
                $('#deleteModal').modal('show');
            });
        }

        // 渲染分页控件
        function renderPagination() {
            const pagination = $('#pagination');
            pagination.empty();
            
            const totalPages = Math.ceil(totalStudents / pageSize);
            
            // 上一页按钮
            const prevLi = $(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `);
            prevLi.on('click', function(e) {
                e.preventDefault();
                if (currentPage > 1) {
                    currentPage--;
                    loadStudents();
                }
            });
            pagination.append(prevLi);
            
            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const li = $(`
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#">${i}</a>
                    </li>
                `);
                li.on('click', function(e) {
                    e.preventDefault();
                    currentPage = i;
                    loadStudents();
                });
                pagination.append(li);
            }
            
            // 下一页按钮
            const nextLi = $(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `);
            nextLi.on('click', function(e) {
                e.preventDefault();
                if (currentPage < totalPages) {
                    currentPage++;
                    loadStudents();
                }
            });
            pagination.append(nextLi);
        }

        // 更新分页信息
        function updatePaginationInfo() {
            const startItem = totalStudents === 0 ? 0 : (currentPage - 1) * pageSize + 1;
            const endItem = Math.min(currentPage * pageSize, totalStudents);
            
            $('#startItem').text(startItem);
            $('#endItem').text(endItem);
            $('#totalItems').text(totalStudents);
        }

        // 编辑学生信息
        function editStudent(studentId) {
            showLoading();
            
            $.ajax({
                url: `${API_BASE_URL}/student/${studentId}`,
                method: 'GET',
                success: function(student) {
                    // 填充表单
                    $('#studentId').val(student.id);
                    $('#name').val(student.name);
                    $('#gender').val(student.gender);
                    $('#age').val(student.age || '');
                    $('#hometown').val(student.hometown || '');
                    $('#phone').val(student.phone || '');
                    
                    // 显示表单
                    showStudentForm();
                    
                    // 滚动到表单位置
                    $('html, body').animate({
                        scrollTop: $('#formContainer').offset().top - 20
                    }, 500);
                },
                error: function(xhr, status, error) {
                    showError('获取学生信息失败: ' + (xhr.responseJSON?.message || error));
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 保存学生信息
        function saveStudent() {
            // 表单验证
            const form = document.getElementById('studentForm');
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }
            
            const studentId = $('#studentId').val();
            const student = {
                name: $('#name').val(),
                gender: $('#gender').val(),
                age: $('#age').val() || null,
                hometown: $('#hometown').val() || null,
                phone: $('#phone').val() || null
            };
            
            const isEdit = !!studentId;
            const url = `${API_BASE_URL}/student`;
            const method = isEdit ? 'PUT' : 'POST';
            
            if (isEdit) {
                student.id = studentId;
            }
            
            showLoading();
            
            $.ajax({
                url: url,
                method: method,
                contentType: 'application/json',
                data: JSON.stringify(student),
                success: function(data) {
                    alert(isEdit ? '修改成功' : '添加成功');
                    hideStudentForm();
                    resetForm();
                    loadStudents();
                },
                error: function(xhr, status, error) {
                    const errorMsg = xhr.responseJSON?.message || error;
                    alert(`${isEdit ? '修改' : '添加'}失败: ${errorMsg}`);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 删除学生
        function deleteStudent(studentId) {
            showLoading();
            
            $.ajax({
                url: `${API_BASE_URL}/student/${studentId}`,
                method: 'DELETE',
                success: function(data) {
                    alert('删除成功');
                    loadStudents();
                },
                error: function(xhr, status, error) {
                    const errorMsg = xhr.responseJSON?.message || error;
                    alert('删除失败: ' + errorMsg);
                },
                complete: function() {
                    hideLoading();
                }
            });
        }

        // 重置表单
        function resetForm() {
            $('#studentForm')[0].reset();
            $('#studentForm').removeClass('was-validated');
            $('#studentId').val('');
        }
    </script>
</body>
</html>